#include "chatwindow.h"
#include "ui_chatwindow.h"
#include <QScrollBar>
#include <QApplication>
#include <QKeyEvent>
#include <QFontComboBox>
#include <QCloseEvent>

ChatWindow::ChatWindow(QWidget *parent) :
        QDialog(parent),
        m_ui(new Ui::ChatWindow)
{
    m_ui->setupUi(this);

    m_ui->sendButton->setEnabled(false);

    nameOfUser = ClientHandler::clientHandlerInstance()->getUsername();
    connect(m_ui->sendButton, SIGNAL(clicked()), this, SLOT(setMessage()));
    connect( ClientHandler::clientHandlerInstance(), SIGNAL(messageReadyForDisplaying()), this, SLOT(displayMessage()));
    connect( m_ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), m_ui->textEdit, SLOT(setCurrentFont(QFont)));

}

ChatWindow::~ChatWindow()
{
    delete m_ui;
}

void ChatWindow::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ChatWindow::closeEvent(QCloseEvent *closed)
{
    ClientHandler::clientHandlerInstance()->setClosedBuddyWindow(this->nameOfContact);
    ClientHandler::clientHandlerInstance()->emitClosedWindow();
}


void ChatWindow::setMessage()
{
    ClientHandler::clientHandlerInstance()->setFrom(nameOfUser);
    ClientHandler::clientHandlerInstance()->setTo(nameOfContact);
    ClientHandler::clientHandlerInstance()->setOutgoingMessage(m_ui->textEdit->toHtml());//toPlainText
    ClientHandler::clientHandlerInstance()->sendMessage();
    m_ui->textEdit->clear();
    m_ui->sendButton->setEnabled(false);
}


void ChatWindow::displayMessage()
{
    // display info only if it is this user
    // or this contact writinga
    if((QString::compare( ClientHandler::clientHandlerInstance()->getFrom(), this->nameOfUser, Qt::CaseSensitive)==0  &&
        QString::compare( ClientHandler::clientHandlerInstance()->getTo(), this->nameOfContact, Qt::CaseSensitive)==0) ||
       (QString::compare( ClientHandler::clientHandlerInstance()->getTo(), this->nameOfUser, Qt::CaseSensitive)==0  &&
        QString::compare( ClientHandler::clientHandlerInstance()->getFrom(), this->nameOfContact, Qt::CaseSensitive)==0))
    {
        QString heading =  ClientHandler::clientHandlerInstance()->getFrom() + " says:";
        m_ui->textBrowser->insertHtml("<b>" + heading + "</b><br>");
        QString theMessage = ClientHandler::clientHandlerInstance()->getIncomingMessage();

        m_ui->textBrowser->insertHtml(theMessage + "<br>");

        QScrollBar *autoScroll = m_ui->textBrowser->verticalScrollBar();
        autoScroll->setValue(autoScroll->maximum());
    }
}

void ChatWindow::on_textEdit_textChanged()
{
    m_ui->sendButton->setEnabled(true);
}

void ChatWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return)
    {
        setMessage();
    }
}
